<template>
  <div>
    <el-row>
      <el-button @click="goBack" icon="el-icon-arrow-left">返回</el-button>
    </el-row>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>变更文档</span>
        <el-upload
          class="upload"
          :action= uploadUrl
          multiple
          :data="{bizId: query.id, bizType: uploadType}"
          :headers="{
            token: token
          }"
          :limit="3"
          :show-file-list="false"
          :on-success="uploadSuccess"
          :on-error="uploadError"
        >
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </div>
      <div class="documentList" v-for="(item, index) in fileList" :key="index">
        <div>{{item.name}}</div>
        <div>
          <el-button type="success" size="mini">
             <a :href="item.url" :download="item.name" class="download">下载</a>
          </el-button>
          <el-button type="danger" size="mini" @click="remove(item.id)">删除</el-button>
        </div>
      </div>
    </el-card>
    <el-card class="box-card content">
      <div slot="header" class="clearfix">
        <span>研发项目管理系统-里程碑变更</span>
      </div>
      <el-table style="width: 100%" :data="tableData">
        <el-table-column type="index" align="center"></el-table-column>
        <el-table-column prop="stageName" label="阶段节点名称" align="center"></el-table-column>
        <el-table-column label="开始时间" align="center">
          <template slot-scope="scope">
            <span v-if="status != 'application'">{{scope.row.planStartDate}}</span>
            <el-date-picker
              v-model="scope.row.planStartDate"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="date"
              placeholder="选择日期"
              size="mini"
              class="datePicker"
              v-else
              align="center"
              :picker-options="pickerOptions"
              @focus="selectDate(scope.$index)"
            ></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="完成时间" align="center">
          <template slot-scope="scope">
            <span v-if="status != 'application'">{{scope.row.planEndDate}}</span>
            <el-date-picker
              v-model="scope.row.planEndDate"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="date"
              placeholder="选择日期"
              size="mini"
              class="datePicker"
              v-else
              align="center"
              :picker-options="pickerOptions1"
              @focus="selectDate(scope.$index)"
            ></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="负责人" align="center">
          <template slot-scope="scope">
            <span v-if="status != 'application'">{{scope.row.managerName}}</span>
            <el-button
              size="mini"
              type="text"
              @click="milestoneSelect(scope.$index)"
              v-else
            >{{scope.row.managerName || '选择'}}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-form ref="form" :model="form1">
        <el-form-item label="完成情况描述">
          <el-input v-model="form1.desc" type="textarea" style="width: 300px;display: block;"></el-input>
        </el-form-item>
      </el-form>
			<div v-for="(item, index) in approveNode" :key="index">
        <div class="documentList">
          <div class="approveNode">{{item.name}}</div>
          <el-button type="text" @click="select(item.name, index)" v-if="item.userList.length == 0" class="name">选择</el-button>
          <div v-else>
            <div v-for="(user, userIndex) in item.userList" :key="user.id" class="name" @click="reselect(index, user.name, userIndex, item.name, item.approveType)">{{user.name}}</div>
            <el-button type="text" @click="select(item.name, index)" v-if="item.approveType == 2 && item.userList.length != 0 && status == 'application'" class="name">选择</el-button>
          </div>
          <div v-if="status != 'application'" class="status">
            <span v-for="user in item.userList" :key="user.id">{{user.approveText}}<span v-if="user.approveOpinion && user.approveStatus == '4'">({{user.approveOpinion}})</span></span>
          </div>
        </div>
      </div>
    </el-card>
    <el-dialog title="选择负责人" :visible.sync="milestoneDialogVisible" width="600px">
      <UserSelect :roleId="roleId" :checkList="checkList" v-if="milestoneDialogVisible" @changeCheckList="changeCheckList" :isSingle="isSingle"></UserSelect>
      <div slot="footer" class="dialog-footer">
        <el-button @click="milestoneDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="selected">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="选择审批人" :visible.sync="dialogVisible" width="600px">
      <UserSelect :roleId="roleId" :checkList="checkList" v-if="dialogVisible" @changeCheckList="changeCheckList" :isSingle="isSingle"></UserSelect>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="selectedRole">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="rejectVisible" >
      <el-input v-model="rejectText" placeholder="请填写驳回理由"></el-input>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="reject">确 定</el-button>
      </div>
    </el-dialog>
    <el-button type="primary" class="commit" @click="milestoneCommit" v-if="!control && this.$route.query.flag == 'application'">提交申请</el-button>
    <el-button type="primary" class="commit" @click="pass" v-if="control">通过</el-button>
    <el-button type="danger" class="commit" @click="rejectVisible = true" v-if="control">驳回</el-button>
  </div>
</template>
<script>
import {storage} from '@/utils';
import approveBase from "../../base/approveBase";
export default {
  mixins: [approveBase],
  data() {
    return {
      milestoneDialogVisible: false,
      tableData: [],
      loading: false,
      users: [],
      user: "",
      index: "",
      pickerOptions: {
        disabledDate: (time) => {
          if (this.tableData[this.index].planStartDate != "" && this.tableData[this.index].planStartDate != null) {
            return time.getTime() > new Date(this.tableData[this.index].planEndDate).getTime();
          }
        }
      },
      pickerOptions1: {
        disabledDate: (time) => {
          return time.getTime() < new Date(this.tableData[this.index].planStartDate).getTime();
        }
      }
    };
  },
  watch: {
    approveTask: function(value) {
      if(this.status == 'appliced') {
        this.tableData = JSON.parse(value.approveRequest.requestParam);
      }
    }
  },
  methods: {
    milestoneSelect(index) {
      this.index = index;
      this.checkList = [];
      if(this.tableData[this.index].managerName) {
        this.checkList = [{
          name: this.tableData[this.index].managerName,
          id: this.tableData[this.index].managerId
        }]
      }
      this.roleId = '1182191961320857601';
      this.milestoneDialogVisible = true;
    },
    selected() {
      this.tableData[this.index].managerName = this.checkList[0].name;
      this.tableData[this.index].managerId = this.checkList[0].id;
      this.milestoneDialogVisible = false;
    },
    getMilestone() {
      let params = {
        projectId: this.$route.query.id
      };
      this.$store.dispatch('project/getMilestone', params).then(res => {
        console.log(res);
        this.tableData = res.filter(item => {
          return item.publishStatus == 2;
        });
      })
    },
    milestoneCommit() {
      let notifyContent = storage.get('loginInfo').userInfoVO.userName + "提交了《" + this.$route.query.name + "》里程碑变更审批";
		 	let selectApproveNode = this.approveNode.map(item => {
        if (item.userList.length === 0) {
          this.$alert("请选择审批人");
          return;
        }
        if (item.approveType == 1) {
          return {
            approveNodeId: item.id,
            userId: item.userList[0].id
          };
        } else {
          return {
            approveNodeId: item.id,
            userIdList: item.userList.map(user => {
              return user.id;
            })
          };
        }
      });
      let params = {
        modelId: $conf.modelId['alteration'], //审批流编号
        bizId: this.query.id, //业务编号
        bizType: $conf.bizType['alteration'], //项目状态
        approveNodeList: selectApproveNode, //审批节点设置集合
        notifyContent: notifyContent,
        requestDescribe: this.form1.desc,
        requestParam: JSON.stringify(this.tableData)
      };
      this.$store.dispatch('project/modifyMilestoneApprove', params).then(res => {
        this.showSuccessMessage('申请变更审批成功');
        this.flag = 'appliced';
        this.getDetailApproveNode($conf.modelId['alteration'], res);
      })
    },
    goBack() {
      this.$router.go(-1);
    },
    getDetailApproveNode(id, bizId) {
      let params = {
        modelId: id
      };
      this.$store.dispatch("project/getApproveNode", params).then(res => {
        this.approveNode = res.map(item => {
          item.userList = [];
          return item;
        });
        this.getDetailUserName(bizId);
      });
    },
    getDetailUserName(id) {
      this.queryApproveById(id).then(res => {
        if(!res) {
          return;
        }
        this.approveTask = res;
        this.form1.desc = res.approveRequest.requestDescribe;
        //根据审批编号获取的当前审批的具体数据，并和审批节点匹配
        res.approveTaskList.forEach(item => {
          this.approveNode.forEach(node => {
            //和审批节点进行匹配
            if (item.nodeName == node.name) {
              node.userList = item.userApproveTaskList.map(el => {
                return {
                  name: el.userName,
                  id: el.userId,
                  approveStatus: el.approveStatus,
                  taskId: el.taskId,
                  approveText: $status.approveText[el.approveStatus],
                  remark: el.remark,
                  createTime: el.createTime,
                  remark: res.approveRequest.requestDescribe
                };
              });
            }
          });
        });
        //判断当前用户有无权限通过或驳回
        this.authority();
      });
    },
    selectDate(index) {
      this.index = index;
    }
  },
  mounted() {
    this.bizType = $conf.bizType['alteration'];
    this.uploadType = $conf.uploadType['review'];
    if(this.$route.query.flag == 'appliced') {
      this.getDetailApproveNode($conf.modelId['alteration'], this.query.approveId);
    } else {
      this.getApproveNode($conf.modelId['alteration']);
      this.getMilestone();
    }
    this.status = this.$route.query.flag;
  }
};
</script>
<style lang="less" scoped>

.datePicker {
  width: 100%;
  max-width: 150px;
}
.documentList {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}
.name {
  width: 50px;
  height: 40px;
}
.approveNode {
  width: 150px;
}
.status {
  width: 100px;
}
.commit {
	margin-top: 30px;
}
.content {
    margin-top: 20px;
}
.commit {
  margin-top: 30px;
}
.box-card {
  position: relative;
  margin-top: 20px;
}
.upload {
  position: absolute;
  right: 15px;
  top: 12px;
}
.download {
  color: #fff;
  text-decoration: none;
}
</style>